'''
 视频拼接
'''
import os

import cv2


# path 原视频所在路径
# newPath 合并后视频所在路径
# notconcatend 原视频最后几秒不参与合并
def lengthenvideo(path, newPath, notconcatend, lengthen):
    if not os.path.exists(newPath):
        os.makedirs(newPath)
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            cam1 = cv2.VideoCapture(os.path.join(path, filename))
            # 获取视频1的宽度
            ww = int(cam1.get(3))
            # 获取视频1的高度
            hh = int(cam1.get(4))
            print(ww, hh)
            # 获取视频的帧频
            CAMERA_FPS = cam1.get(cv2.CAP_PROP_FPS)  # 25帧/秒
            print('帧频:' + str(CAMERA_FPS))
            # 获取视频的帧数
            CAP_PROP_FRAME_COUNT = cam1.get(cv2.CAP_PROP_FRAME_COUNT)  # 25帧/秒
            print("帧数：" + str(CAP_PROP_FRAME_COUNT))
            # 定义视频编码格式
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            # 创建视频保存对象
            videoWriter = cv2.VideoWriter(os.path.join(newPath, filename), fourcc, CAMERA_FPS, (ww, hh))
            # videoWriter = cv2.VideoWriter('C:/Users/Administrator/Desktop/out.wmv', fourcc, CAMERA_FPS,(ww, hh*2))
            for i in range(lengthen):
                print(i)
                cam1 = cv2.VideoCapture(os.path.join(path, filename))
                num = 0
                while True:
                    # 读取视频
                    (ok1, frame1) = cam1.read()
                    # 视频最后一秒不参与合并到新视频
                    if num <= CAP_PROP_FRAME_COUNT - CAMERA_FPS * notconcatend:
                        if ok1:
                            # 重置视频大小，使两视频大小一致
                            # frame1 = cv2.resize(frame1, (ww, hh))
                            # 拼接处理
                            # image = np.concatenate([frame1, frame1, frame1], axis=1)  # axis=0时为垂直拼接；axis=1时为水平拼接
                            # 视频保存
                            videoWriter.write(frame1)
                            if cv2.waitKey(1) & 0xFF == ord('q'):
                                break
                        else:
                            break
                        num += 1
                    else:
                        print(num)
                        break
            videoWriter.release()
            cam1.release()
            cv2.destroyAllWindows()


if __name__ == '__main__':
    path = r'D:\HYLiteResources\video'
    newPath = r'D:\HYLiteResources'
    lengthenvideo(path, newPath, 0, 100)
